import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useParams } from "react-router-dom";
import cloneDeep from "lodash.clonedeep";
import useGlobalSpinner from "../../../hooks/useGlobalSpinner";
import useApi from "../../../apis/hooks/useApi";
import useGetApiConfig from "../../../apis/hooks/useGetApiConfig";
import {
  getMessageWithAgent,
  getMessageWithClient,
} from "../../../apis/sections/applicationView";
import { applicationViewActions } from "../../../store/slices/applicationView-slice";

const useAllMessage = (typeOfCommunication) => {
  const config = useGetApiConfig();
  const dispatch = useDispatch();
  const { applicationId } = useParams();
  const [messageList, setMessageList] = useState([]);

  const choosenFile = useSelector(
    (state) => state.applicationView.choosenFileType
  );

  useEffect(() => {
    if (choosenFile.type) {
      const updateMessageList = cloneDeep(messageList);
      const updateDocList = cloneDeep(
        updateMessageList[choosenFile.index]?.documents
      );

      updateDocList.splice(choosenFile.indexDoc, 1, {
        ...updateDocList[choosenFile.indexDoc],
        documentTypeName: choosenFile.type,
      });

      updateMessageList.splice(choosenFile.index, 1, {
        ...updateMessageList[choosenFile.index],
        documents: updateDocList,
      });

      dispatch(
        applicationViewActions.setChoosenFileType({
          index: null,
          type: "",
        })
      );

      setMessageList(updateMessageList);
    }
  }, [choosenFile.index]);

  const messageApis = {
    Client: getMessageWithClient,
    Agent: getMessageWithAgent,
  };

  const {
    exec: getAllMessages,
    isPending,
    apiStatus,
    error,
  } = useApi(() => messageApis[typeOfCommunication](config, applicationId));

  useGlobalSpinner(isPending);

  const messageListHandler = async () => {
    const { data } = await getAllMessages();

    if (data?.status === 0) {
      setMessageList(data?.data);
    }
  };

  return { isMessageListPending: isPending, messageList, messageListHandler };
};

export default useAllMessage;